package com.woyou.ui.fragment;

import java.util.ArrayList;
import java.util.List;

import retrofit.RetrofitError;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.citaq.ideliver.R;
import com.woyou.bean.CodeResult;
import com.woyou.bean.ReceiveOrderTime;
import com.woyou.bean.UserInfo;
import com.woyou.bean.rpc.orderConfirmReq;
import com.woyou.service.NetWorkCenter;
import com.woyou.ui.activity.orderdetail.OrderDetailActivity;
import com.woyou.ui.api.RefreshOrderDetailsListener;
import com.woyou.ui.view.SuperLayout;
import com.woyou.utils.DateUtils;
import com.woyou.utils.Dialog;
import com.woyou.utils.LogUtil;

/**
 * 及时订单（确认收货的时候）
 * 
 * @author shenzhou 2015年1月16日
 */
public class ConReceivTimeOrder extends SuperLayout {

	private static final String TAG = "ConReceivTimeOrder";

	private ListView mListView;
	private RelativeLayout cancel;
	private RelativeLayout confrim;

	private List<ReceiveOrderTime> variationList = new ArrayList<ReceiveOrderTime>();
	private WaitTimeAdapter timeAdapter;
	private int min;
	private Dialog dialog = new Dialog();
	private RefreshOrderDetailsListener mListener;

	private String oId;

	public void setListener(RefreshOrderDetailsListener mListener) {
		this.mListener = mListener;
	}

	public ConReceivTimeOrder(Context context) {
		super(context);
		initView();
	}

	public ConReceivTimeOrder(Context context, AttributeSet attrs) {
		super(context, attrs);
		initView();
	}

	public ConReceivTimeOrder(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		initView();
	}

	public void show(long acceptTime, String oId) {
		this.oId = oId;
		refreshUI(acceptTime);
		this.setVisibility(View.VISIBLE);
		LogUtil.d(TAG, "acceptTime" + acceptTime);
	}

	public void dismiss() {
		this.setVisibility(GONE);
	}

	public void initView() {
		View view = View.inflate(mContext, R.layout.layout_orderdetails_receive_timegoods, this);
		mListView = (ListView) view.findViewById(R.id.waittime_lv);
		cancel = (RelativeLayout) view.findViewById(R.id.waittime_cancel);
		confrim = (RelativeLayout) view.findViewById(R.id.waittime_ok);
		cancel.setOnClickListener(this);
		confrim.setOnClickListener(this);
		view.findViewById(R.id.conreceive_rl).setOnClickListener(this);
		
		timeAdapter = new WaitTimeAdapter();
		mListView.setAdapter(timeAdapter);
		confrim.setEnabled(false); // 确定按钮不可点击
	}

	private void refreshUI(long acceptTime) {
		int timeInt = Integer.parseInt(DateUtils.StandardFormatStr(acceptTime));
		ReceiveOrderTime orderTime = new ReceiveOrderTime();
		orderTime.setTime(timeInt);
		variationList.add(0, orderTime);

		// for (int i = 10; i <= 60; i+=10) {
		// if( timeInt < i){
		// ReceiveOrderTime time = new ReceiveOrderTime();
		// time.setTime(i);
		// variationList.add(time);
		// }
		// }

		// for (int i = 75; i <= 120; i+=15) {
		// if( timeInt < i){
		// ReceiveOrderTime time = new ReceiveOrderTime();
		// time.setTime(i);
		// variationList.add(time);
		// }
		// }

		// for (int i = 150; i <= 180; i+=30) {
		// if( timeInt < i){
		// ReceiveOrderTime time = new ReceiveOrderTime();
		// time.setTime(i);
		// variationList.add(time);
		// }
		// }

		for (int i = 10; i <= 60; i += 10) {
			ReceiveOrderTime time = new ReceiveOrderTime();
			time.setTime(i);
			variationList.add(time);
		}
		for (int i = 75; i <= 120; i += 15) {
			ReceiveOrderTime time = new ReceiveOrderTime();
			time.setTime(i);
			variationList.add(time);
		}
		for (int i = 150; i <= 180; i += 30) {
			ReceiveOrderTime time = new ReceiveOrderTime();
			time.setTime(i);
			variationList.add(time);
		}

		runOnUI(new Runnable() {

			@Override
			public void run() {
				timeAdapter.notifyDataSetChanged();
			}
		});
	}

	/** 确认收货 */
	@SuppressWarnings("rawtypes")
	private void confirmOrderReport() {
		if (!NetWorkCenter.isNetworkConnected(getContext())) {
			showToastOnUI("网络根本没连,赶紧检查");
			return;
		}

		executeTask(new Runnable() {

			@Override
			public void run() {
				showProgressDialog();
				try {
					orderConfirmReq orderConfirmReq = new orderConfirmReq();
					UserInfo userInfo = mUserModel.getUserInfo();
					if (userInfo != null) {
						orderConfirmReq.setuId(userInfo.getuId());
						orderConfirmReq.setPwd(userInfo.getPwd());
					}
					orderConfirmReq.setoId(oId);
					orderConfirmReq.setMin(min);
					final CodeResult result = mOrderModel.orderConfirm(orderConfirmReq);
					if (result != null && result.getCode() == 1) {
						showToastOnUI("收货成功!");
						// 发送事件刷新订单详情
						if (mListener != null) {
							mListener.callBack(oId);
						}

					} else if (result != null && result.getCode() == -2) {
						showToastOnUI("很抱歉,服务器又任性了");

					} else if (result != null && result.getCode() == -3) {
						runOnUI(new Runnable() {

							@Override
							public void run() {
								dialog.LoginToast(getContext(), result.getMsg(), OrderDetailActivity.class);
							}
						});

					} else {
						showToastOnUI(result.getMsg());

					}
				} catch (RetrofitError e) {
					showToastOnUI("很抱歉,服务器又任性了");
					switch (e.getKind()) {
					case HTTP:
						return;
					case CONVERSION:
						return;
					case NETWORK:
						return;
					case UNEXPECTED:
						return;
					}
				} finally {
					dismissProgressDialog();
				}
			}
		});
	}

	/**
	 * 防止View的事件穿透
	 */
	@SuppressLint("ClickableViewAccessibility")
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		return true;
	}

	public void clear() {
		variationList.clear();
		timeAdapter.notifyDataSetChanged();
		confrim.setEnabled(false);
		confrim.setBackgroundResource(R.color.F0F0F0);
	}

	class WaitTimeAdapter extends BaseAdapter implements OnClickListener {

		@Override
		public int getCount() {
			return variationList.size();
		}

		@Override
		public Object getItem(int position) {
			return variationList.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				convertView = View.inflate(getContext(), R.layout.item_order_waittimes_lv, null);
			}

			TextView time = (TextView) convertView.findViewById(R.id.waittime_time);
			CheckBox checkBox = (CheckBox) convertView.findViewById(R.id.waittime_checkbox);
			ReceiveOrderTime confirmTime = variationList.get(position);
			int itemTime = confirmTime.getTime();
			if (position == 0) {
				time.setText("刚收到(耗时" + itemTime + "分钟)");
			} else if (position > 0 && itemTime < 60) {
				time.setText(itemTime + "分钟");
			} else if (position > 0 && itemTime == 60) {
				time.setText("1小时");
			} else if (position > 0 && itemTime == 75) {
				time.setText("1小时" + "15分钟");
			} else if (position > 0 && itemTime == 90) {
				time.setText("1小时" + "30分钟");
			} else if (position > 0 && itemTime == 105) {
				time.setText("1小时" + "45分钟");
			} else if (position > 0 && itemTime == 120) {
				time.setText("2小时");
			} else if (position > 0 && itemTime == 150) {
				time.setText("2小时" + "30分钟");
			} else if (position > 0 && itemTime == 180) {
				time.setText("3小时");
			}
			RelativeLayout view = (RelativeLayout) convertView.findViewById(R.id.waittime_rl);
			view.setOnClickListener(this);
			view.setTag(confirmTime);

			checkBox.setOnClickListener(this);
			checkBox.setTag(confirmTime);

			boolean flag = confirmTime.isFlag();
			if (flag) {
				checkBox.setBackgroundResource(R.raw.rediobox1);
			} else {
				checkBox.setBackgroundResource(R.raw.rediobox2);
			}
			return convertView;
		}

		@Override
		public void onClick(View v) {
			switch (v.getId()) {

			case R.id.waittime_checkbox:
			case R.id.waittime_rl:
				confrim.setEnabled(true); // 确定按钮可点击
				confrim.setBackgroundColor(Color.WHITE);

				closeAll();
				ReceiveOrderTime tag = (ReceiveOrderTime) v.getTag();
				tag.setFlag(true);
				min = tag.getTime();
				timeAdapter.notifyDataSetChanged();
				break;

			}
		}

		private void closeAll() {
			for (ReceiveOrderTime time : variationList) {
				time.setFlag(false);
			}
		}

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.waittime_ok:
			confirmOrderReport();
			clear();
			this.setVisibility(View.GONE);
			break;

		case R.id.waittime_cancel:
			clear();
			this.setVisibility(View.GONE);
			break;

		case R.id.conreceive_rl:
			this.setVisibility(View.GONE);
			break;

		default:
			break;
		}
	}

}
